<?php
///
namespace lxsphp\Core;

use lxsphp\App;

/**
 * 核心 - [钩子]类
 *
 * @version $Id: Hook.php 175 2014-07-16 10:21:58Z linsir123 $
 * @package lxsphp\Core
 */
class Hook
{
	/**
	 * 配置
	 *
	 * @var array
	 */
	public $conf = array();

	/**
	 * 勾子列表
	 *
	 * @var array
	 */
	private $_list = array(
		// 初始化
		'Init' => array(),

		// 消息派发之前
		'Dispatcher' => array(),

		// 应用周期结束
		'End' => array(),

		// 记录日志
		'Log' => array(),
	);

	/**
	 * 初始化
	 */
	public function init()
	{
		///
		$this->conf = App::o("app.hook");
		$keys = array_keys($this->_list);
		foreach ($this->conf as $key => $list) {
			if (! in_array($key, $keys))
				continue;

			///
			foreach ($list as $v) {
				$class = sprintf("app\\Hook\\%s\\%s", $key, $v);
				if (is_subclass_of($class, 'lxsphp\Core\IHook')) {
					$o = App::$I->singleton($class);
					$this->addHook($key, array($o, 'handle'));
				}
				else {
					// var_dump('Hook Miss');
				}
			}
		}

		///
		$this->activeHook('Init');
	}

	/**
	 * 注册勾子
	 *
	 * @param string $hook 勾子名称
	 * @param callback $callback 回调
	 */
	public function addHook($hook, $callback)
	{
		///
		if (array_key_exists($hook, $this->_list) && is_callable($callback))
			$this->_list[$hook][] = $callback;
	}

	/**
	 * 执行某个勾子
	 *
	 * @param string $hook 勾子名称
	 * @param mixed $params 参数
	 * @param mixed $return 是否返回
	 *
	 * @return mixed
	 */
	public function activeHook($hook, $params = null, $return = false)
	{
		///
		$needArgs = ! empty($params);
		$list = isset($this->_list[$hook]) ? $this->_list[$hook] : array();

		///
		foreach ($list as $callback) {
			$args = $needArgs ? array($params) : array();
			$params = call_user_func_array($callback, $args);
		}

		///
		return $return ? $params : null;
	}
}

/**
 * Class IHook
 *
 * @package lxsphp\Core
 */
abstract class IHook
{
	/**
	 * @return mixed
	 */
	abstract public function handle();
}
